const User = require('../models/user');

exports.form = (req, res) => {
    res.render('register', {
        title: 'Register'
    });
};

exports.submit = (req, res, next) => {
    const data = req.body.user; //从表单获取数据
    User.getByName(data.name, (err, user) => { //从name获取user对象
        if (err) return next(err);
        // redis will default it
        if (user.id) {
            res.error('Username already taken!'); //已存在该用户
            res.redirect('back');
        } else {
            user = new User({
                name: data.name,
                pass: data.pass
            });
            user.save((err) => { //保存 数据
                if (err) return next(err);
                req.session.uid = user.id; //session 设置用户id
                res.redirect('/');
            });
        }
    });
};